package v1

import (
	"go-pioneer/internal/dtos"
	"go-pioneer/internal/service"
	"go-pioneer/pkg/errorcode"
	"go-pioneer/pkg/response"

	"github.com/gin-gonic/gin"
)

type ExampleHandler struct {
	svc service.ExampleService
}

func NewExampleHandler(svc service.ExampleService) *ExampleHandler {
	return &ExampleHandler{
		svc: svc,
	}
}

func (h *ExampleHandler) RegisterRoutes(r *gin.Engine) {
	apiV1Group := r.Group("/api/v1")
	{
		apiV1Group.POST("/example", h.CreateExample)
		apiV1Group.GET("/example/:id", h.GetExample)
	}
}

func (h *ExampleHandler) CreateExample(ctx *gin.Context) {
	newResponse := response.NewResponse(ctx)
	bindReq := new(dtos.ExampleReq)
	if err := ctx.ShouldBindJSON(bindReq); err != nil {
		newResponse.ToErrorResponse(errorcode.RequestParamValidationErrorCode)
		return
	}

	err := h.svc.CreateExample(ctx, *bindReq)
	if err != nil {
		newResponse.ToErrorResponse(err.(*errorcode.Error))
		return
	}

	newResponse.ToResponseSuccess(nil)
}

func (h *ExampleHandler) GetExample(ctx *gin.Context) {
	newResponse := response.NewResponse(ctx)
	id := ctx.Param("id")

	example, err := h.svc.GetExample(ctx, id)
	if err != nil {
		newResponse.ToErrorResponse(err.(*errorcode.Error))
		return
	}

	newResponse.ToResponseSuccess(example)
}
